import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'

import store from '@/store'
import { getLocalStorage } from '@/utils/auth.js'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  baseURL: '/api',
  timeout: 30000,
  // 禁用 Cookie 等信息
  // withCredentials: false,
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    // if (config.url == '/linchuang/lc_login') {
    //   refreshWeb()
    // }
    return config
  },
  (error) => {
    Message({
      message: msg,
      type: 'error',
    })
    console.log(error)
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  async (res) => {
    return res.data
  },
  (error) => {
    let { message } = error
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.substr(message.length - 3) == 401) {
      message = error.response.data.info
      Message({
        message: message,
        type: 'error',
      })
      router.push('/login')
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    if (error.response.data.info) {
      message = error.response.data.info
    }
    Message({
      message: message,
      type: 'error',
    })
    return Promise.reject(error)
  }
)

// function refreshWeb() {
//   let oldTime = getLocalStorage('time')
//   let newTime = Date.parse(new Date())
//   console.log(newTime)
//   if (newTime - oldTime > 5) {
//     store.dispatch('login', {
//       yhm: store.getters.yhm,
//       password: store.getters.password,
//     })
//   }
// }

export default service
